package com.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.conf.Constant;

import java.util.Calendar;
import java.util.Map;

/**
 * @author 王乾
 * @comments Jwt工具类
 * @date 2024-05-10 23:15:23
 */
public class UtilJwt {

    /**
     * @author 王乾
     * @comments 生成token
     * @date 2024/5/11 10:08
     * @modification
     */
    public static String getToken(Map<String,Object> map,String secret){
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.HOUR, 24);
        return JWT.create().withHeader(map)
                .withClaim(Constant.UserId, map.get(Constant.UserId).toString())
                .withClaim(Constant.Nickname, map.get(Constant.Nickname).toString())
                .withClaim(Constant.Phone, map.get(Constant.Phone).toString())
                .withExpiresAt(instance.getTime())
                .sign(Algorithm.HMAC256(secret));
    }

    /**
     * @author 王乾
     * @comments 解析账号
     * @date 2024/5/11 9:58
     * @modification
     */

    public static String getUsername(String secret,String token){
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(secret)).build();
        DecodedJWT decodedJWT = jwtVerifier.verify(token);
        return decodedJWT.getClaim(Constant.Nickname).asString();
    }

    /**
     * @author 王乾
     * @comments 解析手机号
     * @date 2024/5/11 9:58
     * @modification
     */

    public static String getPhone(String secret,String token){
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(secret)).build();
        DecodedJWT decodedJWT = jwtVerifier.verify(token);
        return decodedJWT.getClaim(Constant.Phone).asString();
    }

    /**
     * @author 王乾
     * @comments 解析账号id
     * @date 2024/5/11 9:58
     * @modification
     */

    public static String getUserid(String secret,String token){
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(secret)).build();
        DecodedJWT decodedJWT = jwtVerifier.verify(token);
        return decodedJWT.getClaim(Constant.UserId).asString();
    }

    /**
     * @author 王乾
     * @comments 签名校验
     * @date 2024/5/11 11:24
     * @modification
     */
    public static boolean checkSign(String secret,String token){
        try {
            JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(secret)).build();
            jwtVerifier.verify(token);
            return true;
        } catch (IllegalArgumentException e) {
            return false;
        } catch (JWTVerificationException e) {
            return false;
        }
    }
}
